package pers.kw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Service;
import pers.kw.config.oauth.context.MyParamValue;
import pers.kw.config.oauth.context.MyParamValueThreadLocal;
import pers.kw.contants.AuthParamName;
import pers.kw.crm.dto.UserDto;
import pers.kw.entity.TokenDto;
import pers.kw.feign.CrmUserApiService;
import pers.kw.protocol.R;
import pers.kw.service.UserDetailStrategy;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 前台用户处理
 */
@Service
public class WebUserDetailStrategyService implements UserDetailStrategy {

    private static final Logger log = LoggerFactory.getLogger(WebUserDetailStrategyService.class);

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private CrmUserApiService crmUserApiService;

    @Override
    public User getUserInfoByMobile(String userNo, List<GrantedAuthority> authorities) {
        log.info("前台系统登录-用户信息查验start...参数:{}", userNo);
        R<UserDto> resp = crmUserApiService.getUserInfo(userNo);
        log.info("查询用户信息响应：{}", JSON.toJSONString(resp));
        if (!resp.isOk()) {
            throw new OAuth2Exception(resp.getMsg());
        }
        //密码需要md5,之后再BCryptPasswordEncoder 加密
        UserDto body = resp.getBody();
        if (body == null) {
            throw new OAuth2Exception("用户不存在");
        }
        if (StringUtils.isBlank(body.getUserPwd())) {
            throw new OAuth2Exception("用户信息异常，未设置初始密码");
        }
        return new User(userNo, body.getUserPwd(), authorities);
    }

    @Override
    public Map<String, Object> initTokenInfo(MyParamValue paramValue) {
        MyParamValue myParamValue = MyParamValueThreadLocal.getCurrent();
        String userNo = myParamValue.getAuthParameter("username");
        String userType = myParamValue.getAuthParameter(AuthParamName.USER_TYPE);
        R<UserDto> resp = crmUserApiService.getUserInfo(userNo);
        if (!resp.isOk()) {
            throw new OAuth2Exception(resp.getMsg());
        }
        UserDto userDto = resp.getBody();
        TokenDto tokenDTO = new TokenDto();
        tokenDTO.setUserNo(userDto.getUserNo());
        tokenDTO.setUserName(userDto.getUserName());
        tokenDTO.setUserType(userType);
        tokenDTO.setMobile(userDto.getUserMobile());
        return JSONObject.parseObject(JSONObject.toJSONString(tokenDTO),
                new TypeReference<Map<String, Object>>() {
                });
    }
}
